#include "MessageWidget.h"
#include <QPixmap>

MessageWidget::MessageWidget(const model::Message& message, bool isOwnMessage, QWidget* parent)
    : QWidget(parent), m_message(message), m_isOwnMessage(isOwnMessage)
{
    setupUI();
}

void MessageWidget::setupUI()
{
    if (m_isOwnMessage) {
        setupOwnMessageUI();
    }
    else {
        setupOtherMessageUI();
    }
}

void MessageWidget::setupOwnMessageUI()
{
    auto* mainLayout = new QHBoxLayout(this);

    // 消息内容在右侧
    auto* messageLayout = new QVBoxLayout();

    m_nameLabel = new QLabel(m_message.sender.nickname + " (我)");
    m_nameLabel->setStyleSheet("color: #666; font-size: 12px;");
    m_nameLabel->setAlignment(Qt::AlignRight);

    m_contentLabel = new QLabel(QString::fromUtf8(m_message.content));
    m_contentLabel->setStyleSheet(
        "background: #95ec69;"
        "padding: 8px 12px;"
        "border-radius: 8px;"
        "max-width: 300px;"
    );
    m_contentLabel->setWordWrap(true);

    m_timeLabel = new QLabel(m_message.time);
    m_timeLabel->setStyleSheet("color: #999; font-size: 11px;");
    m_timeLabel->setAlignment(Qt::AlignRight);

    messageLayout->addWidget(m_nameLabel);
    messageLayout->addWidget(m_contentLabel);
    messageLayout->addWidget(m_timeLabel);

    // 头像在右侧
    m_avatarLabel = new QLabel();
    m_avatarLabel->setFixedSize(40, 40);
    m_avatarLabel->setStyleSheet("border-radius: 20px; background: #ddd;");

    mainLayout->addStretch();
    mainLayout->addLayout(messageLayout);
    mainLayout->addWidget(m_avatarLabel);
    mainLayout->setContentsMargins(10, 5, 10, 5);
}

void MessageWidget::setupOtherMessageUI()
{
    auto* mainLayout = new QHBoxLayout(this);

    // 头像在左侧
    m_avatarLabel = new QLabel();
    m_avatarLabel->setFixedSize(40, 40);
    m_avatarLabel->setStyleSheet("border-radius: 20px; background: #ddd;");

    // 消息内容在右侧
    auto* messageLayout = new QVBoxLayout();

    m_nameLabel = new QLabel(m_message.sender.nickname);
    m_nameLabel->setStyleSheet("color: #666; font-size: 12px;");
    m_nameLabel->setAlignment(Qt::AlignLeft);

    m_contentLabel = new QLabel(QString::fromUtf8(m_message.content));
    m_contentLabel->setStyleSheet(
        "background: white;"
        "padding: 8px 12px;"
        "border-radius: 8px;"
        "max-width: 300px;"
    );
    m_contentLabel->setWordWrap(true);

    m_timeLabel = new QLabel(m_message.time);
    m_timeLabel->setStyleSheet("color: #999; font-size: 11px;");
    m_timeLabel->setAlignment(Qt::AlignLeft);

    messageLayout->addWidget(m_nameLabel);
    messageLayout->addWidget(m_contentLabel);
    messageLayout->addWidget(m_timeLabel);

    mainLayout->addWidget(m_avatarLabel);
    mainLayout->addLayout(messageLayout);
    mainLayout->addStretch();
    mainLayout->setContentsMargins(10, 5, 10, 5);
}
